package site.zhangzhuo.v2;

import java.io.*;
import java.util.HashMap;

//心
public class Xin implements Serializable {
    @Serial
    private static final long serialVersionUID = 21L;

    private final HashMap<Character, Zi> wanfa = new HashMap<>();

    //心的大小，字的数量
    public int size() {
        return wanfa.size();
    }

    //添加从眼获得的内容
    public void getYanshi(Yan yan) {
        Zi qian=null,hou=null;
        for (Character c : yan.getYanshi().toCharArray()) {
            //循环中hou永远不会是null
            //qian如果是null表示是开头，统一为'^'字
            hou=wanfa.computeIfAbsent(c,k->new Zi(k));
            if(null==qian){
                hou.addQian(new Zi('^'));
            }else{
                hou.addQian(qian);
                qian.addHou(hou);
            }
            qian=hou;
        }
    }

    public static Xin load(String filename) {
        System.out.println("------reSerialized read Xin---------" + filename);
        try {
            FileInputStream fileIn = new FileInputStream(filename);
            ObjectInputStream in = new ObjectInputStream(fileIn);
            Xin xin = (Xin) in.readObject();
            in.close();
            fileIn.close();
            return xin;
        } catch (IOException i) {
            i.printStackTrace();
        } catch (ClassNotFoundException c) {
            System.out.println("class not found");
            c.printStackTrace();
        }
        return null;
    }

    //序列化到文件
    public void save(String filename) {
        System.out.println("------Serialized save Xin V2---------" + filename);
        try {
            FileOutputStream fileOut = new FileOutputStream(filename);
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(this);
            out.close();
            fileOut.close();
        } catch (IOException i) {
            i.printStackTrace();
        }
    }

    @Override
    public String toString(){
        StringBuilder str=new StringBuilder();
        for(Zi z:wanfa.values()){
            str.append(z.toString());
        }
        return str.toString();
    }
}
